package com.skp.shaphan.io;

import java.awt.Color;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Table;
import com.lowagie.text.rtf.RtfWriter2;
import com.lowagie.text.rtf.document.RtfDocument;
import com.lowagie.text.rtf.table.RtfCell;
import com.lowagie.text.rtf.table.RtfTable;
import com.skp.job.ProjectJobException;

public class RtfDataWriter extends ExportDataWriter {
	private Document doc;
	private Table table;
	private RtfWriter2 writer;
	private int columnCount = 1;

	@Override
	protected void createStreams(OutputStream stream) throws IOException {
		System.out.println("Creating table with " + columnCount + " columns");
		try {
			table = new Table(columnCount);
			table.setTableFitsPage(true);
			table.setBorderWidth(1);
			table.setBorderColor(Color.black);
		} catch (BadElementException e) {
			throw new IOException(e);
		}
		
		doc = new Document();
		writer = RtfWriter2.getInstance(doc, stream);
		doc.open();
	}

	@Override
	public void close() throws IOException {
		table.complete();
		System.out.println("close() -- columns = " + table.getColumns() + "; size = " + table.size());
		try {
			doc.add(table);
		} catch (DocumentException e) {
			throw new IOException(e);
		}
		doc.close();
		writer.flush();
		writer.close();
		super.close();
	}

	@Override
	public void setMetaData(ResultSetMetaData meta) throws SQLException {
		super.setMetaData(meta);
		columnCount = meta.getColumnCount();
	}

	@Override
	protected void writeCellData(String data, int columnNumber) {
		System.out.println("Writing cell #" + columnNumber + " = '" + data + "'");
		super.writeCellData(data, columnNumber);
		try {
			Chunk chunk = new Chunk(data);
			RtfCell cell = new RtfCell(chunk);
			table.addCell(cell);
		} catch (BadElementException e) {
			ProjectJobException.displayException(e);
		}
	}

	@Override
	protected void writeHeadingCellData(String data) {
		super.writeHeadingCellData(data);
		Chunk chunk = new Chunk(data);
		RtfCell cell;
		try {
			cell = new RtfCell(chunk);
			table.addCell(cell);
		} catch (BadElementException e) {
			ProjectJobException.displayException(e);
		}
	}

}
